package com.szgd.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by dong on 2018/2/27.
 */
@Component
public class FileUtil {


    public String uploadFile(InputStream is, String fileName,String date) throws FileNotFoundException, IOException {

        String fileUploadPath = PropertiesUtil.get("uploadPath");
        File fileUploadDir = new File(fileUploadPath);
        if (!fileUploadDir.isDirectory()) {
            fileUploadDir.mkdir();
        }

        String subPath = createSubFolder(fileUploadDir.getPath(),SysUtil.getDateStr(null,"yyyyMM"));

        //String nameArray[] = fileName.split("\\.");
        int index =  fileName.lastIndexOf(".");

        String newFileName = null;
        if (date != null)
            newFileName = fileName.substring(0,index) + "-" + date + "." + fileName.substring(index+1,fileName.length());
        else
            newFileName = fileName.substring(0,index)  + "." + fileName.substring(index+1,fileName.length());
        FileOutputStream fos = new FileOutputStream(fileUploadPath + File.separator + subPath + File.separator+ newFileName);

        byte[] b = new byte[1024];
        while ((is.read(b)) != -1) {
            fos.write(b);
        }

        fos.close();
        is.close();

        return newFileName;
    }

    public String uploadPic(InputStream is, String fileName) throws FileNotFoundException, IOException {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = df.format(new Date());
        int index =  fileName.lastIndexOf(".");
        String newFileName = fileName.substring(0,index) + "-" + date + "." + fileName.substring(index+1,fileName.length());
        String fileUploadPath = PropertiesUtil.get("uploadPath");
        File fileUploadDir = new File(fileUploadPath);
        if (!fileUploadDir.isDirectory()) {
            fileUploadDir.mkdir();
        }
        String subPath = createSubFolder(fileUploadDir.getPath(),SysUtil.getDateStr(null,"yyyyMM"));
        FileOutputStream fos = new FileOutputStream(fileUploadPath + File.separator + subPath + File.separator + newFileName);
        byte[] b = new byte[1024];
        while ((is.read(b)) != -1) {
            fos.write(b);
        }
        fos.close();
        is.close();
        return newFileName;
    }

    public String uploadFile(String imgBase64, String fileName,String date,String basePath) throws FileNotFoundException, IOException {

        String fileUploadPath = basePath;//PropertiesUtil.get("uploadPath");
        File fileUploadDir = new File(fileUploadPath);
        if (!fileUploadDir.isDirectory()) {
            fileUploadDir.mkdir();
        }

        String subPath = createSubFolder(fileUploadDir.getPath(),SysUtil.getDateStr(null,"yyyyMM"));

        //String nameArray[] = fileName.split("\\.");
        int index =  fileName.lastIndexOf(".");

        String newFileName = null;
        if (date != null)
            newFileName = fileName.substring(0,index) + "-" + date + "." + fileName.substring(index+1,fileName.length());
        else
            newFileName = fileName.substring(0,index)  + "." + fileName.substring(index+1,fileName.length());
        //FileOutputStream fos = new FileOutputStream(fileUploadPath + File.separator + subPath + File.separator+ newFileName);

        boolean result = ImageUtil.generateImageByStr(imgBase64,fileUploadPath + File.separator + subPath + File.separator+ newFileName);
        if (!result)
            return null;
        return newFileName;
    }

    public static String appShowPic(String path,String name,String fileUploadPath, HttpServletResponse response) {
        try {
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/octet-stream ");
            response.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
            response.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
            response.setContentType("multipart/form-data");
            response.setContentType("UTF-8");

            String filePath = FileUtil.existFile(fileUploadPath,path,name);
            InputStream inputStream = new FileInputStream(filePath +  File.separator + name);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String uploadFile(byte[] imgByteArray, String fileName,String date,String basePath) throws FileNotFoundException, IOException {

        String fileUploadPath = basePath;//PropertiesUtil.get("uploadPath");
        File fileUploadDir = new File(fileUploadPath);
        if (!fileUploadDir.isDirectory()) {
            fileUploadDir.mkdir();
        }

        String subPath = createSubFolder(fileUploadDir.getPath(),SysUtil.getDateStr(null,"yyyyMM"));

        //String nameArray[] = fileName.split("\\.");
        int index =  fileName.lastIndexOf(".");

        String newFileName = null;
        if (date != null)
            newFileName = fileName.substring(0,index) + "-" + date + "." + fileName.substring(index+1,fileName.length());
        else
            newFileName = fileName.substring(0,index)  + "." + fileName.substring(index+1,fileName.length());
        //FileOutputStream fos = new FileOutputStream(fileUploadPath + File.separator + subPath + File.separator+ newFileName);
        InputStream in = new ByteArrayInputStream(imgByteArray);
        File file = new File(fileUploadPath + File.separator + subPath + File.separator+ newFileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();
            return newFileName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 保存从外部结果导入的文件

     * @return
     * @throws FileNotFoundException
     * @throws IOException
     *//*
    public String importFile(InputStream is, String fileName,String date) throws FileNotFoundException, IOException {

        File fileUploadDir = new File(fileImportPath);
        if (!fileUploadDir.isDirectory()) {
            fileUploadDir.mkdir();
        }
        String subPath = createSubFolder(fileUploadDir.getPath(),SysUtil.getDateStr(null,"yyyyMM"));

        String nameArray[] = fileName.split("\\.");

        String newFileName = nameArray[0] + "-" + date + "." + nameArray[1];

        File file=new File(fileImportPath + File.separator + subPath + File.separator + newFileName);
        if(!file.exists())
        {
            FileOutputStream fos = new FileOutputStream(fileImportPath + File.separator + subPath + File.separator+ newFileName);

            byte[] b = new byte[1024];
            int len = 0 ;
            while ((len = is.read(b)) != -1) {
                fos.write(b,0, len);
            }

            fos.close();
            is.close();

        }

        return newFileName;
    }*/

    public static InputStream downloadFile(String subPath,String fileName) throws FileNotFoundException{
        String fileUploadPath = PropertiesUtil.get("uploadPath");
        return new FileInputStream(fileUploadPath + File.separator + subPath +  File.separator + fileName);
    }

    public static byte[] getFileByte(String basePath, String subPath,String fileName) throws FileNotFoundException{
        String fileUploadPath = basePath;//PropertiesUtil.get("uploadPath");
        File file = new File(fileUploadPath + File.separator + subPath +  File.separator + fileName);
        byte[] buffer = null;
        FileInputStream fis;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
//            if(file.exists()) {
//                file.delete();
//            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;


    }

    public static boolean deleteFile(String fullPath) {
        File file = new File(fullPath);
        String fileName = file.getName();
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            System.gc();
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    public static boolean moveFile(String srcFullPath, String dstDir) {
        File srcFile = new File(srcFullPath);
        if (!srcFile.exists() || srcFile.isDirectory()) {
            return false;
        }

        String fileName = srcFile.getName();
        String dstFullPath = dstDir + "\\" + fileName;
        File dstFile = new File(dstFullPath);
        if (srcFile.renameTo(dstFile)) {// 直接重命名绝对路径速度更快
            return true;
        }else
            return false;
    }

/*    public void saveDocuments(MultipartFile[] improtFiles, String[] targetCorp_FileNameArray, String targetCorp, String date) throws IOException {
        String failedFilename = null;
        String susscessFilename = null;
        for (MultipartFile file : improtFiles) {//循环每个导入的文件
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream is = file.getInputStream();
            for (int i = 0; i < targetCorp_FileNameArray.length; i++) {//循环找出此文件对应哪个查找类型，什么文件格式
                String targetCorp_FileName = targetCorp_FileNameArray[i];
                if (targetCorp_FileName.split("_").length == 3)//说明是其他类型的文件，上传保存
                {
                    if (targetCorp_FileName.indexOf(targetCorp) >= 0)//当前数组元素包含此文件名
                    {
                        this.importFile(file.getInputStream(),fileName,date);
                    }
                }
            }
        }
    }*/



    public  static void copyFileToFolder(String sourceFilePath, String destFolderPath)throws IOException {
        //1.获取源文件的名称
        String newFileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/")+1); //目标文件地址
        String desFilePath = destFolderPath + File.separator + newFileName; //源文件地址
        // 打开输入流
        FileInputStream fis = new FileInputStream(sourceFilePath);
        // 打开输出流
        FileOutputStream fos = new FileOutputStream(desFilePath);

        // 读取和写入信息
        int len = 0;
        // 创建一个字节数组，当做缓冲区
        byte[] b = new byte[1024];
        while ((len = fis.read(b)) != -1) {
            fos.write(b, 0, len);
        }
        // 关闭流  先开后关  后开先关
        fos.close(); // 后开先关
        fis.close(); // 先开后关
    }


    public static  String createSubFolder(String parentPath, String subFolderName) throws IOException {
        String folderPath = parentPath + "\\" + subFolderName;
        File file = new File(folderPath);
        if (!file.exists()) {//如果文件夹不存在
            file.mkdirs();//创建文件夹
        }
        return  subFolderName;
    }

    /**
     * 判断文件是否存在，如果存在，返回所在目录,原来文件是直接放在基本目录下，后来又增加了日期目录
     * @param basePath
     * @param subPath
     * @param fileName
     * @return
     */
    public static String existFile(String basePath, String subPath,String fileName) {
        String fullpath = basePath + File.separator + subPath ;

        File file = new File(fullpath+File.separator + fileName);
        if(file.exists())
        {
        }
        else
        {
            fullpath = basePath ;
            file = new File(fullpath + File.separator + fileName);
            if(file.exists())
            {

            }else
                fullpath = "";
        }

        return fullpath;
    }
    public static void main(String args[]) throws Exception
    {
        String fileName = "BA111_IA2222";
        String path = "d:";
        //String content = "13391011778,13391011779,13391011780,13391011775";
        //moveFile("D:\\BA111_IA2222.xlsx","E:");
        //FileUtil.createSubFolder("D:/szgd-snap-image11","123");
        String s = "abc";
        System.out.println(s.split(",")[0]);

        //readFromMDExcel("美达","d:","xlsx");
        //readFromDDExcel("滴滴","d:","xlsx");
    }
}

